package com.maxmlr.net.rpc;

import com.google.protobuf.Value;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName Remote
 * @Description TODO
 * @Author maxiao
 * @Date 2020/4/4 下午9:21
 * @Version V1.0
 */
public class RemoteInvocationHandler implements InvocationHandler {

    private String host;
    private int port;

    public RemoteInvocationHandler(String host, int port) {
        this.host = host;
        this.port = port;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        List<Value> values = new ArrayList<>();
        for (Object o : args) {
            if (o.getClass() == String.class) {
                values.add(Value.newBuilder().setStringValue((String) o).build());
            } else if (o.getClass() == Integer.class) {
                values.add(Value.newBuilder().setNumberValue((Integer) o).build());
            } else {
                values.add(Value.newBuilder().setStringValue((String) o).build());
            }
        }

        Rpc.RpcRequest rpcRequest = Rpc.RpcRequest.newBuilder()
                .setServiceName(method.getDeclaringClass().getName())
                .setMethodName(method.getName())
                .addAllArgs(values)
                .build();

        TcpClient tcpClient = new TcpClient(this.host, this.port);

        Value build = tcpClient.send(rpcRequest);

        return build.getStringValue();
    }
}
